<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\Logger\SLogger;
use App\Models\Orm\Banner;
use App\Models\Orm\Candy;
use App\Models\Orm\CoinLog;
use App\Models\Orm\Grade;
use App\Models\Orm\Market;
use App\Models\Orm\AwAuditRecord;
use App\Models\Orm\CooperativeCompany;
use App\Models\Orm\Pay;
use App\Models\Orm\User;
use App\Models\Orm\UserCoinLog;
use Illuminate\Foundation\Bootstrap\HandleExceptions;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Exceptions\HandlerException;
/**
 * 产品模块控制器
 *
 * Class ProductController
 * @package App\Http\Controllers\Admin
 */
class OrderController extends Controller
{
    /**
     * 产品列表(展示页)
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $user = auth('admin')->user();

        $data = CoinLog::where('status','>',0)->orderby('id', 'desc')->get();
        return view('admin.order.index', compact('data'));

    }


    /**
     * 驳回多条提现记录
     *
     * @param Request $request
     * @return array
     */
    public function rejectRecords(Request $request)
    {
        /**
         * 验证提交的参数withdraw_id_list,否则异常
         * 遍历所有提现记录id
         *      获取提现记录,判断是否为待处理,否则异常
         *      获取用户信息、用户资金统计数据
         *      变更用户资金统计数据:用户余额、冻结金额
         *      往资金记录日志表插入一条被驳回的数据
         *      更新这条提现记录状态为驳回
         *      保存用户资金统计数据
         */

        DB::beginTransaction();

        try {
            if (!$request->has('withdraw_id_list')) {
                throw new HandlerException('未传递参数', 1000);
            }

            $withdraw_id_list = $request->input('withdraw_id_list');

            if (empty($withdraw_id_list)) {
                throw new HandlerException('未传递参数', 1000);
            }

            // ID去重
            $withdraw_id_list = array_unique($withdraw_id_list);


            foreach ($withdraw_id_list as $k=> $withdraw_id) {

                if($withdraw_id == 'on'){

                    continue;
                }

                // 提现记录初始化
                $withdraw = CoinLog::find($withdraw_id);

                if ($withdraw->status != CoinLog::APPLY) {
                    throw new HandlerException("该提现记录状态不可更改-提现记录ID:{$withdraw->id}", 1000);
                }

                // 资金记录日志表插入数据(提现被驳回)
                $account_log = new UserCoinLog();
                $account_log->user_id = $withdraw->user_id;
                $account_log->action = UserCoinLog::ACTION_WITHDRAW;
                $account_log->order_id = $withdraw->id;
                $account_log->type = UserCoinLog::TYPE_CUT;
                $account_log->status = UserCoinLog::STATUS_FAILED;
                $account_log->number = $withdraw->number;
                $account_log->created_at = date('Y-m-d H:i:s');
                $account_log->save();

                // 这条提现记录状态改为驳回
                $withdraw->status = UserCoinLog::STATUS_FAILED;

                $withdraw->updated_at = date('Y-m-d H:i:s');


                $withdraw->save();


            }

            DB::commit();

            return [
                'code' => 0,
                'msg' => '',
            ];

        } catch (\Exception $e) {

            DB::rollback();

            SLogger::getStream()->error('驳回提现记录操作失败', [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
            ]);

            if ($e instanceof HandlerException) {
                return [
                    'code' => $e->getCode(),
                    'msg' => $e->getMessage(),
                ];
            } else {
                return [
                    'code' => $e->getCode(),
                    'msg' => '服务器内部错误,请稍后重试或联系技术人员处理',
                ];
            }
        }
    }


    /**
     * 放款多条提现记录
     *
     * @param Request $request
     * @return array
     */
    public function lendRecords(Request $request)
    {
        /**
         * 验证提交的参数withdraw_id_list,否则异常
         * 遍历所有提现记录id
         *      获取提现记录,判断是否为待处理,否则异常
         *      获取用户信息、用户资金统计数据
         *      变更用户资金统计数据:冻结金额、提现总额
         *      往资金记录日志表插入一条被驳回的数据
         *      更新这条提现记录状态为驳回
         *      保存用户资金统计数据
         */

        DB::beginTransaction();

        try {
            if (!$request->has('withdraw_id_list')) {
                throw new HandlerException('未传递参数', 1000);
            }

            $withdraw_id_list = $request->input('withdraw_id_list');

            if (empty($withdraw_id_list)) {
                throw new HandlerException('未传递参数', 1000);
            }

            // ID去重
            $withdraw_id_list = array_unique($withdraw_id_list);

            foreach ($withdraw_id_list as $withdraw_id) {

                if($withdraw_id == 'on'){

                    continue;
                }

                // 提现记录初始化
                $withdraw = CoinLog::find($withdraw_id);


                if ($withdraw->status != CoinLog::APPLY) {
                    throw new HandlerException("该提现记录状态不可更改-提现记录ID:{$withdraw->id}", 1000);
                }

                // 用户初始化
                $user = User::find($withdraw->user_id);

                $user -> total_bi += $withdraw->number;

                $user -> save();

                // 资金记录日志表插入数据(提现被放款)
                $account_log = new UserCoinLog();
                $account_log->user_id = $withdraw->user_id;
                $account_log->action = UserCoinLog::ACTION_WITHDRAW;
                $account_log->order_id = $withdraw->id;
                $account_log->type = UserCoinLog::TYPE_CUT;
                $account_log->status = UserCoinLog::STATUS_ACCESS;
                $account_log->number = $withdraw->number;
                $account_log->created_at = date('Y-m-d H:i:s');
                $account_log->save();

                // 这条提现记录状态改为已放款
                $withdraw->status = UserCoinLog::STATUS_ACCESS;

                $withdraw->updated_at = date('Y-m-d H:i:s');

                $withdraw->save();


            }

            DB::commit();

            return [
                'code' => 0,
                'msg' => '',
            ];

        } catch (\Exception $e) {

            DB::rollback();

            SLogger::getStream()->error('放款提现记录操作失败', [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
            ]);

            if ($e instanceof HandlerException) {
                return [
                    'code' => $e->getCode(),
                    'msg' => $e->getMessage(),
                ];
            } else {
                return [
                    'code' => $e->getCode(),
                    'msg' => '服务器内部错误,请稍后重试或联系技术人员处理',
                ];
            }
        }
    }

    public function create(Request $request, $id)
    {


        if ($request->isMethod('post')) {

            $request->flash();

            $insert_data = $request->except(['_token', 'image','s']);

            $data['type'] = 3;
            $insert_data['order_id'] = self::createNid();
            $insert_data['status'] = CoinLog::MAN;
            $insert_data['created_at'] = date('Y-m-d H:i:s');

//            dd($insert_data);
            CoinLog::create($insert_data);

            $user = User::where('id',$insert_data['user_id'])->first();
            $user -> total_bi +=$insert_data['number'];
            $user ->save();
            return redirect('/admin/order/index')->with(['success' => '您的申请已提交,请耐心等等待审核']);
        }

        $data = CoinLog::find($id);

        return view('admin.order.create', compact('data'));

    }



    public static function createNid($action_code = '1001')
    {
        /**
         * 格式: 当前日期+动作码+当前时间戳最后5位+10位随机数
         * 长度: 27位
         * 动作码对照:
         *      1001 : 提现
         */
        $nid = date('Ymd');
        $nid .= strval($action_code);
        $nid .= substr(time(), 5, 9);
        $nid .= mt_rand(1000000000, 9999999999);

        return $nid;
    }



    public function edit(Request $request, $id)
    {


        if ($request->isMethod('post')) {

            $request->flash();

            $insert_data = $request->except(['_token', 'image','s']);

                    DB::beginTransaction();
        try {
            $data['type'] = 3;
            $insert_data['order_id'] = self::createNid();
            $insert_data['status'] = CoinLog::DRAW;
            $insert_data['state'] = 2;
            $insert_data['created_at'] = date('Y-m-d H:i:s');

//            dd($insert_data);
            CoinLog::create($insert_data);

            $user = User::where('id', $insert_data['user_id'])->first();
            $user->total_bi -= $insert_data['number'];
            if ($user->total_bi < 0) {
                DB::rollBack();
                return back()->withErrors('提币数量不足!');

            }
            $result = $user->save();
            if($result)
            {
                DB::commit();
            }
            DB::rollback();
        }catch (\Exception $e){

            DB::rollBack();
            return back()->withErrors('提币数量不足!');

        }
            return redirect('/admin/order/index')->with(['success' => '您的申请已提交,请耐心等等待审核']);
        }

        $data = CoinLog::find($id);

        return view('admin.order.edit', compact('data'));

    }


}